<?php

namespace App\Http\Controllers\Api;

use App\Config;
use App\SubjectSort;
use App\TalentsSystemOrder;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class SubjectPowerController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 购买评估机会
     * sort_id  购买哪套题目  题目分类id
     */
    public function buy(Request $request)
    {
        $sort = $request->sort_id;//购买哪套题目  题目分类id
        $subjectSort = SubjectSort::find($sort);
        if (!$subjectSort) {
            return response(['message' => '评估类型不存在', 'order' => []], 400);
        }
        $data = [];
        $data['user_id'] = Auth::id();
        $data['order_number'] = time() . rand(10000, 99999);//订单号
        $data['goods_name'] = '购买' . $subjectSort->name . '评估题目';//商品名称
        $data['price'] = $subjectSort->price;//金额
        $data['subject_sort_id'] = $sort;//题目分类
        $order = TalentsSystemOrder::create($data);
        if ($order) {
            return response(['message' => '生成订单成功', 'order' => $order]);
        }
        return response(['message' => '系统繁忙', 'order' => []], 400);
    }

    /**
     * @return mixed
     * 获取团队评估单价===一个人需要多少钱
     */
    public function getTeamUnit()
    {
        return Config::where('key', 'team_price')->value('value');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 团队评估
     * team_user_id   团队id   array
     */
    public function team(Request $request)
    {
        if (!$request->team_user_id || !is_array($request->team_user_id)) {
            return response(['message' => '请输入用户id', 'order' => []], 400);
        }
        foreach ($request->team_user_id as $v) {
            if (!User::find($v)) {
                return response(['message' => '用户' . $v . '不存在', 'order' => []], 400);
                break;
            }
        }
        $price = Config::where('key', 'team_price')->value('value') * count($request->team_user_id);//价格
        if ($price <= 0) {
            return response(['message' => '系统繁忙', 'order' => []], 400);
        }
        $data = [];
        $data['user_id'] = Auth::id();
        $data['order_number'] = time() . rand(10000, 99999);//订单号
        $data['goods_name'] = '购买团队评估';//商品名称
        $data['price'] = $price;//金额
        $data['team_user_id'] = implode(',', $request->team_user_id);//用户id
        $order = TalentsSystemOrder::create($data);
        if ($order) {
            return response(['message' => '生成订单成功', 'order' => $order]);
        }
        return response(['message' => '系统繁忙', 'order' => []], 400);
    }
}
